package top.chengdongqing.mishop.common.exception

import jakarta.servlet.http.HttpServletRequest
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import java.time.LocalDateTime

@RestControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException::class)
    fun handleException(
        e: RuntimeException,
        request: HttpServletRequest,
    ): ResponseEntity<ExceptionResponse> {
        // 获取响应状态码
        var status = HttpStatus.INTERNAL_SERVER_ERROR
        if (e is BaseException) {
            status = e.code
        }
        // 构建响应实体
        val response = ExceptionResponse(e.message, status, status.value(), request.requestURI)

        return ResponseEntity(response, status)
    }

    data class ExceptionResponse(
        val message: String?,
        val error: HttpStatus,
        val status: Int,
        val path: String,
        val timestamp: LocalDateTime = LocalDateTime.now()
    )
}